package service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import bean.GoodsDetails;
import bean.TxtContent;
import javafx.concurrent.Task;
import util.PropertyUtil;

/**
 * txt文件转换成xml文件处理
 * @author Administrator
 *
 */
public class MyTask extends Task<String> {
	
	private List<String> fileList;

	public MyTask(List<String> fileList) {
		this.fileList = fileList;
	}

	@Override
	protected String call() throws Exception {
		// TODO Auto-generated method stub
		if(fileList.isEmpty()){
			//文件为空
			return "请选择至少一个文件";
		}else{
			for (String txtName : fileList) {
				//获取根路径文件夹名称
				String txtPath = PropertyUtil.getKeyValue("txtPath");
				File file = new File(txtPath+"\\"+txtName);
				if(!file.exists()||!file.isFile()){
					//文件不存在
					return txtName+"文件不存在";
				}else{
					//解析Excel文件
					//解析txt文件
					TxtContent txtContent = parseTxt(file);
					if(txtContent.getBz()==null||txtContent.getBz().equals("")){
						//文件格式不正确
						return txtName+"文件格式不正确";
					}
					//生成xml文件
					Boolean flag = createXml(txtContent);
					if(flag){
						//生成成功，删除原文件
						file.delete();
					}else{
						//生成失败
						return txtName+"生成失败";
					}
				}
			}
		}
		//执行成功
		return "生成成功";
	}
	
	/**
	 * 生成xml文件
	 * @param txtContent
	 * @return
	 * @throws IOException 
	 */
	private Boolean createXml(TxtContent txtContent){
		Document document = DocumentHelper.createDocument();
		document.setXMLEncoding("UTF-8");
		Element root = document.addElement("Kp");
		
		root.addElement("Version").addText(txtContent.getVersion());
		Element fpxx = root.addElement("Fpxx");
		fpxx.addElement("Zsl").addText(txtContent.getZsl());
		Element fp = fpxx.addElement("Fpsj").addElement("Fp");
		fp.addElement("Djh").addText(txtContent.getDjh());
		fp.addElement("Gfmc").addText(txtContent.getGfmc());
		fp.addElement("Gfsh").addText(txtContent.getGfsh());
		fp.addElement("Gfdzdh").addText(txtContent.getGfdzdh());
		fp.addElement("Gfyhzh").addText(txtContent.getGfyhzh());
		fp.addElement("Bz").addText(txtContent.getBz());
		fp.addElement("Fhr").addText(txtContent.getFhr());
		fp.addElement("Skr").addText(txtContent.getSkr());
		fp.addElement("Hsbz").addText(txtContent.getHsbz());
		fp.addElement("Spbmbbh").addText(txtContent.getSpbmbbh());
		Element spxx = fp.addElement("Spxx").addAttribute("Sph", txtContent.getSph());
		List<GoodsDetails> goodsList = txtContent.getGoodsList();
		for (GoodsDetails goodsDetails : goodsList) {
			Element sph = spxx.addElement("Sph");
			sph.addElement("Xh").addText(goodsDetails.getXh());
			sph.addElement("Spmc").addText(goodsDetails.getSpmc());
			sph.addElement("Ggxh").addText(goodsDetails.getGgxh());
			sph.addElement("Jldw").addText(goodsDetails.getJldw());
			sph.addElement("Sl").addText(goodsDetails.getSl());
			sph.addElement("Spbm").addText(goodsDetails.getSpbm());
			sph.addElement("Qyspbm").addText("");
			sph.addElement("Syyhzcbz").addText(goodsDetails.getSyyhzcbz());
			sph.addElement("Lslbz").addText("");
			sph.addElement("Yhzcsm").addText("");
			sph.addElement("Kce").addText(goodsDetails.getKce());
			sph.addElement("Dj").addText(goodsDetails.getDj());
			sph.addElement("Slv").addText(goodsDetails.getSlv());
			sph.addElement("Se").addText(goodsDetails.getSe());
			sph.addElement("Je").addText( goodsDetails.getJe());
		}
		
		String outPutPath = PropertyUtil.getKeyValue("outPutPath");
		String xmlFile = outPutPath+"\\发票号"+txtContent.getDjh()+".xml";
		
		try {
			FileOutputStream fos = new FileOutputStream(xmlFile);  
			OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");  
			OutputFormat of = new OutputFormat();  
			of.setEncoding("UTF-8");  
			of.setIndent(true);  
			of.setIndent("    ");  
			of.setNewlines(true);  
			XMLWriter writer = new XMLWriter(osw, of);  
			writer.write(document);  
			writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}    
		return true;
	}
	
	
	
	/**
	 * 读取txt文件内容
	 * @param file
	 * @return
	 * @throws IOException
	 */
	private TxtContent parseTxt(File file) throws IOException {
		InputStreamReader read = new InputStreamReader(new FileInputStream(file),"gbk");//考虑到编码格式
        BufferedReader bufferedReader = new BufferedReader(read);
        String lineTxt = null;
        int step = 0;
        TxtContent content = new TxtContent();
        List<GoodsDetails> list = new ArrayList<GoodsDetails>();
        //读第一行跳过
        bufferedReader.readLine();
        //读第二行
        lineTxt = bufferedReader.readLine();
        String[] str = lineTxt.split("~~");
        if(str.length>1){
        	//20170701版本使用
			content.setDjh(str[0]);
			//content.setSph(str[1]);
			content.setGfmc(str[3]);
			content.setGfsh(str[10]);
			content.setGfdzdh(str[11]+" "+str[12]);
			content.setGfyhzh(str[13]+" "+str[14]);
			content.setBz(str[15]);
        	
        	//20170625版本使用
        	/*content.setDjh(str[0]);
        	//content.setSph(str[1]);
        	content.setGfmc(str[3]);
        	content.setGfsh("");
			content.setGfdzdh("");
			content.setGfyhzh("");
			String bz = null;
			for (int i = 3; i < str.length; i++) {
				if(!str[i].equals("")){
					bz = str[i];
				}
			}
			int i = bz.indexOf("~");
			if(i==-1){
				content.setBz(bz.substring(0, bz.length()));
			}else{
				content.setBz(bz.substring(i+1,bz.length()));
			}*/
        	
        	while((lineTxt = bufferedReader.readLine()) != null){
        		if(lineTxt.equals("")){
        			break;
        		}
        		step++;
        		str = lineTxt.split("~~");
        		GoodsDetails good = new GoodsDetails();
        		good.setXh(String.valueOf(step));
        		good.setSpCode(str[0]);
        		good.setSpmc(str[1]);
        		good.setJldw(str[2]);
        		good.setGgxh(str[3]);
        		good.setSl(str[4]);
        		//含税金额
        		BigDecimal mon = new BigDecimal(str[5]);
        		//数量
        		BigDecimal num = new BigDecimal(str[4]);
        		//税率
        		BigDecimal tax = new BigDecimal(str[7]);
        		//税额
        		BigDecimal se = mon.divide(new BigDecimal(1).add(tax), 10, BigDecimal.ROUND_HALF_EVEN)
        				.multiply(tax).setScale(10, BigDecimal.ROUND_HALF_EVEN);
        		
        		BigDecimal je = mon.subtract(se);
        		
        		//单价
        		good.setDj(je.divide(num, 14, BigDecimal.ROUND_HALF_EVEN).toString());
        		good.setMon(str[5]);
        		good.setSe(se.toString());
        		good.setJe(je.toString());//str[6]
        		good.setSlv(str[7]);
        		String spbm = str[10];
        		//添加0处理
        		//spbm = handleZero(spbm);
        		good.setSpbm(spbm);
        		list.add(good);
        	}
        }
        content.setSph(String.valueOf(step));
    	content.setGoodsList(list);
	    read.close();
	    return content;
        }
	
	/**
	 * 补零操作
	 * @param spbm
	 * @return
	 */
	/*private String handleZero(String spbm) {
		int temp = 19 - spbm.length();
		for (int i = 0; i < temp; i++) {
			spbm = spbm+"0";
		}
		return spbm;
	}*/
	
}
